package com.xiguthings.waka.web.controller.task;

import javax.annotation.Resource;

import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.exception.BussinessException;
import com.xiguthings.waka.po.Paper;
import com.xiguthings.waka.po.PaperExample;
import com.xiguthings.waka.po.PaperTask;
import com.xiguthings.waka.po.PaperTaskExample;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.web.controller.paper.PaperVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.service.paper.IPaperService;
import com.xiguthings.waka.service.task.ITaskService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/task")
@Api(tags = "task")
public class TaskController extends AbstractController {
    @Resource
    private ITaskService taskService;


    /**
     * 创建查询条件
     *
     * @param taskVo
     * @param example
     * @throws NumberFormatException
     */
    private void queryConditions(TaskVo taskVo, PaperTaskExample example) throws NumberFormatException {

        PaperTaskExample.Criteria criteria = example.createCriteria();
        // 如果查询条件为空的
        if (taskVo == null) {
            // 则查询所有未被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
            return;
        }

        // 如果有查询条件
        PaperTask task = taskVo.getPaperTask();
        // 添加查询条件
        if (task != null) {
            if (StringUtils.isNotBlank(task.getTaskId())) {
                criteria.andTaskIdEqualTo(task.getTaskId());
            }
            if (StringUtils.isNotBlank(task.getPaperId())) {
                criteria.andPaperIdEqualTo(task.getPaperId());
            }
            if (StringUtils.isNotBlank(task.getDescr())) {
                criteria.andDescrLike(("%" + task.getDescr() + "%"));
            }
        }

        if (StringUtils.isNotBlank(taskVo.getInStatus())) {
            // 添加包含的状态
            String statuses = taskVo.getInStatus();
            String[] statusArr = statuses.split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String str : statusArr) {
                statusList.add(new Integer(str));
            }
            criteria.andStatusIn(statusList);
        } else {
            // 如果状态的查询条件是空的，则查询没有被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
        }


    }


    /**
     * 修改或者添加
     *
     * @param taskVo
     * @return
     * @throws Exception
     */
    @ApiOperation(tags = {
            "1.控制台"}, value = "修改/添加", httpMethod = "POST", notes = "修改时，必须填写“paperTask.taskId”参数。<br>添加新记录时，paperId必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperTask.taskId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperTask.paperId", value = "所属的试卷的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperTask.descr", value = "描述", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperTask.status", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query")
    })
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity save(@ApiIgnore TaskVo taskVo) throws Exception {
        if (taskVo == null || taskVo.getPaperTask() == null) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "无法操作空参数");
        }

        PaperTask task = taskVo.getPaperTask();
        String id = task.getTaskId();
        String msg = null;
        if (StringUtils.isNotBlank(id)) {
            // 修改
            int row = taskService.updateByPrimaryKeySelective(task);
            if (row > 0) {
                msg = "修改成功";
            } else {
                msg = "修改失败，数据库中可能不存在这条数据";
            }
        } else {
            if (StringUtils.isBlank(task.getPaperId())) {
                BussinessException.throwThis(CODE_EMPTY_REQUIRED, "paperId为空，必须指定所属的试卷");
            }
            int row = taskService.insert(task);
            if (row > 0) {
                msg = "添加成功";
            } else {
                msg = "添加失败，重试";
            }
        }
        return ajaxReturnMap(CODE_SUCCESS, msg, task.getTaskId());
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "taskId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperTask.taskId", value = "主键id", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseEntity detail(@ApiIgnore TaskVo taskVo) throws Exception {
        if (taskVo == null
                || taskVo.getPaperTask() == null
                || StringUtils.isBlank(taskVo.getPaperTask().getTaskId())) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "请指定taskId");
        }

        PaperTask task = taskService.selectByPrimaryKey(taskVo.getPaperTask().getTaskId());
        return ajaxReturnMap(CODE_SUCCESS, null, task);
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "删除", httpMethod = "GET", notes = "taskId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperTask.taskId", value = "主键id", dataType = "String", required = true, paramType = "query")})
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@ApiIgnore TaskVo taskVo) throws Exception {
        if (taskVo == null
                || taskVo.getPaperTask() == null
                || StringUtils.isBlank(taskVo.getPaperTask().getTaskId())) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "请指定taskId");
        }

        int row = taskService.deleteByPrimaryKey(taskVo.getPaperTask().getTaskId());
        String msg = null;
        if (row > 0) {
            msg = "删除成功";
        } else {
            msg = "在此之前可能已经删除了这条数据";
        }
        return ajaxReturnMap(CODE_SUCCESS, msg, null);
    }

    /**
     * 分页查询
     *
     * @param taskVo
     * @param page
     * @return
     * @throws Exception
     */

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperTask.taskId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperTask.paperId", value = "所属的试卷的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperTask.descr", value = "描述", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "inStatus", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query"),
//            @ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/pagelist")
    @ResponseBody
    public ResponseEntity pageList(@ApiIgnore TaskVo taskVo, @ApiIgnore Page page) throws Exception {
        PaperTaskExample example = new PaperTaskExample();
        queryConditions(taskVo, example);
        super.selectByPage(page, example, taskService);
        return ajaxReturnMap(CODE_SUCCESS, null, page);
    }
}
